import un from '@uni-helper/uni-network'
import qs from 'qs'
import pkg from '@/../package.json'
import { useAppStore, useUserStore } from '@/store'
import { DefaultBaseUrl, DefaultHeaders } from './config'

const instance = un.create({
  baseUrl: DefaultBaseUrl,
  timeout: 30_000,
  paramsSerializer: (params: any) => {
    const query = qs.stringify(
      Object.fromEntries(
        Object.entries(params).filter(
          ([, v]) => !['undefined', 'null', undefined, null].includes((v as any)?.toString() ?? v),
        ),
      ),
    )
    return query
  },
})

instance.interceptors.request.use((config) => {
  const userStore = useUserStore()
  const appStore = useAppStore()
  config.headers = {
    ...DefaultHeaders,
    Authorization: `${userStore.token}`,
    "X-Platform": appStore.sysInfo.uniPlatform,
    'X-Version': `${appStore.pkgname||pkg.name}/${pkg.version}`,
    // #ifdef APP-PLUS
    "X-Channel": plus?.runtime?.channel,
    // #endif
    ...config.headers,
  }
  return config
})
instance.interceptors.response.use(
  (response) => {
    const data = response as IUnResponse
    if (data?.status !== 200) {
      console.error('api response status error, url=', data?.config?.url, data)
    }
    return data
  },
  (error) => {
    const response = error.response
    // console.error('api response error, url=', response?.config?.url, response)
    if (response?.status === 401) {
      // 保留当前页面，跳转到登录页，登录成功后返回当前页面
      uni.navigateTo({ url: `/pages/login/login` })
    }
    else {
      uni.showToast({
        title: response?.data?.msg || '系统错误',
        icon: 'none',
      })
    }
    return Promise.reject(error)
  },
)

// uniapp 网络请求实例
export { instance as unir }
